package com.hhkj.admin.student.service.biz.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.hhkj.admin.student.domain.Student;
import com.hhkj.admin.student.domain.StudentCourseTrainCount;
import com.hhkj.admin.student.model.extend.StudentCourseTrainModel;
import com.hhkj.admin.student.model.req.StudentLoginLogReq;
import com.hhkj.admin.student.model.res.TrainDetailRes;
import com.hhkj.admin.student.service.base.StudentLoginLogService;
import com.hhkj.admin.student.service.biz.TrainCountBizService;
import com.hhkj.admin.student.service.extend.TrainCountExtendService;
import com.hhkj.admin.train.common.component.supplier.TrainCountSupplier;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.SysUserCodeConstants;
import com.ruoyi.common.cont.SysConst;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.StudentLoginLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 学员培训统计BizService接口
 *
 * @author ruoyi
 * @since 2023-06-08
 */
@Slf4j
@Service
public class TrainCountBizServiceImpl implements TrainCountBizService {
    @Autowired
    private StudentLoginLogService studentLoginLogService;
    @Autowired
    private TrainCountExtendService trainCountExtendService;
    @Autowired
    private TrainCountSupplier trainCountSupplier;

    /**
     * 查询学员练习情况
     *
     * @param countParam 传参
     * @return 学员练习情况
     */
    @Override
    public TableDataInfo pagePracticeCount(StudentCourseTrainCount countParam) {
        long startTime = System.currentTimeMillis();
        //查询学员
        List<Student> students = trainCountExtendService.selectStudentList(countParam);
        long endTime = System.currentTimeMillis();
        log.info("程序运行时间： " + (endTime - startTime) + "ms");
        List<StudentCourseTrainCount> studentCourseTrainCounts = applyTrainQuestionInfo(students, SysConst.OPERATE.PAGE.getCode());
        //创建返回分页实体
        return createPageBody(studentCourseTrainCounts, students);
    }

    /**
     * 分页实体创建
     *
     * @param practiceCounts 返回记录
     * @param students       实际查出来的记录
     * @return 分页实体
     */
    private TableDataInfo createPageBody(List<StudentCourseTrainCount> practiceCounts, List<Student> students) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(practiceCounts);
        rspData.setTotal(new PageInfo(students).getTotal());
        return rspData;
    }


    /**
     * 为查询出的学员补充上关联练习信息
     *
     * @param students    查询出的学员
     * @param operateFlag 操作标志 page分页，export导出
     */
    private List<StudentCourseTrainCount> applyTrainQuestionInfo(List<Student> students, String operateFlag) {
        List<StudentCourseTrainCount> practiceCounts = Lists.newArrayList();
        if (students != null && !students.isEmpty()) {
            //遍历学员
            StudentCourseTrainCount trainCount;
            List<Long> studentIdList = new ArrayList<>();
            List<Long> courseIdList = new ArrayList<>();
            for (Student student : students) {
                trainCount = new StudentCourseTrainCount();
                trainCount.setStudentId(student.getId());
                trainCount.setStudentName(student.getName());
                trainCount.setCourseId(student.getCourseId());
                trainCount.setCourseName(student.getCourseName());
                //管理员才展示所属机构名称
                trainCount.setInsName(SysUser.isAdminTypeCode(SecurityUtils.getTypeCode()) ? student.getInsName() : null);
                trainCount.setBatchNum(student.getBatchNum());
                studentIdList.add(student.getId());
                courseIdList.add(student.getCourseId());
                practiceCounts.add(trainCount);
            }
            trainCountSupplier.supplyLoginInfo(practiceCounts, studentIdList);
            trainCountSupplier.supplyPractiseCount(practiceCounts, studentIdList, courseIdList);
            trainCountSupplier.supplyLastTest(practiceCounts, studentIdList, courseIdList);
            if (SysConst.OPERATE.EXPORT.getCode().equals(operateFlag)) {
                trainCountSupplier.supplyTrainDetail(practiceCounts, studentIdList, courseIdList);
            }
        }
        return practiceCounts;
    }

    /**
     * 导出学员练习情况
     *
     * @param countParam 传参
     * @return 学员练习情况 Workbook
     */
    @Override
    public Workbook exportPracticeCount(StudentCourseTrainCount countParam) {
        //查询学员列表
        List<Student> students = trainCountExtendService.selectStudentList(countParam);
        List<StudentCourseTrainCount> studentCourseTrainCounts = applyTrainQuestionInfo(students, SysConst.OPERATE.EXPORT.getCode());
        return createStudentTrainWorkbook(studentCourseTrainCounts);
    }

    /**
     * 生成表格workbook
     *
     * @param studentCourseTrainCounts 学员练习情况
     * @return 学员练习情况 Workbook
     */
    private Workbook createStudentTrainWorkbook(List<StudentCourseTrainCount> studentCourseTrainCounts) {
        Workbook workbook = null;
        //管理员比普通角色多一列，使用不同model
        if (SysUserCodeConstants.UserCode.ADMIN.getCode().equals(SecurityUtils.getTypeCode())) {
            workbook = ExcelExportUtil.exportExcel(new ExportParams(StudentCourseTrainCount.TITLE_NAME,
                    StudentCourseTrainCount.SHEET_NAME), StudentCourseTrainCount.class, studentCourseTrainCounts);
        } else {
            List<StudentCourseTrainModel> collect = studentCourseTrainCounts
                    .stream()
                    .map(o -> {
                        StudentCourseTrainModel model = new StudentCourseTrainModel();
                        BeanUtil.copyProperties(o, model);
                        return model;
                    }).collect(Collectors.toList());
            workbook = ExcelExportUtil.exportExcel(new ExportParams(StudentCourseTrainModel.TITLE_NAME,
                    StudentCourseTrainModel.SHEET_NAME), StudentCourseTrainModel.class, collect);
        }
        return workbook;
    }

    /**
     * 查询学员登录日志
     *
     * @param studentLoginLogReq 传参
     * @return 学员登录日志
     */
    @Override
    public List<StudentLoginLog> pageLoginLog(StudentLoginLogReq studentLoginLogReq) {
        List<StudentLoginLog> studentLoginLogList = studentLoginLogService.list(Wrappers.<StudentLoginLog>lambdaQuery()
                .eq(StudentLoginLog::getStudentId, studentLoginLogReq.getStudentId())
                .eq(StudentLoginLog::getCourseId, studentLoginLogReq.getCourseId())
                .orderByDesc(StudentLoginLog::getLoginTime));
        return studentLoginLogList;
    }

    /**
     * 查询培训详情
     *
     * @param trainCount 传参
     * @return 培训详情列表
     */
    @Override
    public List<TrainDetailRes> pageTrainDetail(StudentCourseTrainCount trainCount) {
        //查询培训详情
        return trainCountExtendService.pageTrainDetail(trainCount);
    }


}
